package com.forest.gissingle;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.forest.gissingle.dialog.BigBanDialog;
import com.forest.gissingle.dialog.PositionsDialog;
import com.forest.gissingle.dialog.RoadsDialog;
import com.forest.gissingle.dialog.TreesDialog;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.CameraPosition;

public class MainActivity extends FragmentActivity implements
		OnCameraChangeListener, LocationSource, LocationListener,
		OnClickListener {
	private GoogleMap map;

	Location latestLocation = null;
	OnLocationChangedListener mLocationListener;
	private LocationManager locationManager;

	Button btnMarkers, btnLayers, btnLocation, btnBigBan, btnSmallBan,
			btnTrees, btnRoad, btnPosition;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initID();
		// 暂时取消添加地图（模拟器报错）
		testAvail();
		googleMap();
	}

	/**
	 * 初始化ID
	 */
	private void initID() {
		btnMarkers = (Button) findViewById(R.id.btn_title_markers);
		btnLayers = (Button) findViewById(R.id.btn_title_layers);
		btnLocation = (Button) findViewById(R.id.btn_title_location);
		btnBigBan = (Button) findViewById(R.id.button1);
		btnSmallBan = (Button) findViewById(R.id.button2);
		btnTrees = (Button) findViewById(R.id.button3);
		btnRoad = (Button) findViewById(R.id.button4);
		btnPosition = (Button) findViewById(R.id.button5);
		btnMarkers.setOnClickListener(this);
		btnLayers.setOnClickListener(this);
		btnLocation.setOnClickListener(this);
		btnBigBan.setOnClickListener(this);
		btnSmallBan.setOnClickListener(this);
		btnTrees.setOnClickListener(this);
		btnRoad.setOnClickListener(this);
		btnPosition.setOnClickListener(this);
	}

	private void testAvail() {
		int errorCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this); // 如果无法启动，则按照原因显示说明
		if (ConnectionResult.SUCCESS != errorCode) {
			GooglePlayServicesUtil.getErrorDialog(errorCode, this, 0).show();
		}

	}

	private void googleMap() {

		if (map == null) {
			// normal get
			map = ((SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map)).getMap();
			// mMap = ((MapFragment)
			// getFragmentManager().findFragmentById(R.id.map)).getMap();
		}
		map.setMyLocationEnabled(true);
		map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
		map.setLocationSource(this);
		UiSettings uiSetting = map.getUiSettings();
		// uiSetting.setZoomControlsEnabled(false);
		// uiSetting.setMyLocationButtonEnabled(arg0)
		// 显示缩放大小
		map.setOnCameraChangeListener(this);

		setIconPos();

		// animeMap
		// // Move the camera instantly to Sydney with a zoom of 15.
		// map.moveCamera(CameraUpdateFactory.newLatLngZoom(SYDNEY, 15));
		// // Zoom in, animating the camera.
		// map.animateCamera(CameraUpdateFactory.zoomIn());
		// // Zoom out to zoom level 10, animating with a duration of 2 seconds.
		// map.animateCamera(CameraUpdateFactory.zoomTo(10),2000, null);
		// // Construct a CameraPosition focusing on Mountain View and animate
		// the
		// // camera to that position.
		// CameraPosition cameraPosition = new CameraPosition.Builder()
		// .target(MOUNTAIN_VIEW) // Sets the center of the map to Mountain
		// // View
		// .zoom(17) // Sets the zoom
		// .bearing(90) // Sets the orientation of the camera to east
		// .tilt(30) // Sets the tilt of the camera to 30 degrees
		// .build(); // Creates a CameraPosition from the builder
		// map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

		// MapFragment mMapFragment = MapFragment.newInstance();
		// FragmentTransaction fragmentTransaction = getFragmentManager()
		// .beginTransaction();
		// fragmentTransaction.add(R.id.my_container, mMapFragment);
		// fragmentTransaction.commit();

		// Add markers
		// map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
		// "Hello world"));
		// Marker melbourne = map.addMarker(new MarkerOptions()
		// .position(MELBOURNE)
		// .title("Melbourne")
		// .snippet("Population: 4,137,400")
		// .icon(BitmapDescriptorFactory
		// .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
		// map.setOnMarkerClickListener(this);
		// .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)

		requestLocation();

	}

	private void requestLocation() {
		// TODlocationManager = (LocationManager)
		// getSystemService(LOCATION_SERVICE);

		// You may want to pass a different provider in as the first arg here
		// depending on the location accuracy that you desire
		// see LocationManager.getBestProvider()
		if (locationManager == null) {
			locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		}
		Criteria locationCriteria = new Criteria();
		// locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
		locationManager.requestLocationUpdates(
				locationManager.getBestProvider(locationCriteria, true), 1L,
				// LocationManager.GPS_PROVIDER, 1L,
				2F, this);
		locationManager.requestLocationUpdates(
		// locationManager.getBestProvider(locationCriteria, true), 1L,
				LocationManager.GPS_PROVIDER, 1L, 2F, this);
		// setUpMapIfNeeded();
		// writeBitmap();O Auto-generated method stub

	}

	/**
	 * 设置定位按钮与放大按钮位置
	 */
	private void setIconPos() {
		// Gets the my location button
		View myLocationButton = this.findViewById(R.id.map).findViewById(2);

		// Checks if we found the my location button
		if (myLocationButton != null) {
			// Sets the margin of the button
			ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(
					myLocationButton.getLayoutParams());
			marginParams.setMargins(0, 100, 20, 0);
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
					marginParams);
			layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
					RelativeLayout.TRUE);
			myLocationButton.setLayoutParams(layoutParams);
		}

		View zoomControl = this.findViewById(R.id.map).findViewById(1);

		// Checks if we found the my location button
		if (zoomControl != null) {
			// Sets the margin of the button
			ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(
					zoomControl.getLayoutParams());
			marginParams.setMargins(0, 0, 20, 100);
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
					marginParams);
			layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
					RelativeLayout.TRUE);
			layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,
					RelativeLayout.TRUE);
			zoomControl.setLayoutParams(layoutParams);
		}

	}

	@Override
	public void onPause() {
		// ---------------------------google-----------------------
		if (locationManager != null) {
			locationManager.removeUpdates(this);
		}
		super.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
		// ---------------------------google-----------------------
		// setUpMapIfNeeded();
		if (locationManager != null) {
			requestLocation();
			map.setMyLocationEnabled(true);
		}
	}

	@Override
	public void onCameraChange(CameraPosition arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void activate(OnLocationChangedListener listener) {
		mLocationListener = listener;
	}

	@Override
	public void deactivate() {
		mLocationListener = null;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	// @Override
	// public void onLocationChanged(Location location) {
	// /**
	// * Location[mProvider=network,mTime=1306399187835,mLatitude=24.9692934,
	// * mLongitude
	// * =121.23618125,mHasAltitude=false,mAltitude=0.0,mHasSpeed=false
	// * ,mSpeed=
	// * 0.0,mHasBearing=false,mBearing=0.0,mHasAccuracy=true,mAccuracy
	// * =60.0,mExtras=Bundle[mParcelledData.dataSize=148]]
	// */
	// // Toast.makeText(this,
	// // Utils.getDistance(110.313, 21.705, 85.74, 29.64) + "---",
	// // Toast.LENGTH_LONG).show();
	// if (mLocationListener != null) {
	// // 设置当前最近位置
	// latestLocation = location;
	// // 设置定位信息
	// mLocationListener.onLocationChanged(location);
	// Log.d("GTest", "getProvider=" + location.getProvider()
	// + "getLatitude经=" + location.getLatitude()// 经度
	// + "getLongitude纬=" + location.getLongitude() // 纬度
	// + "getAccuracy=" + location.getAccuracy());
	//
	// // 暂时取消定位
	// // Move the camera to the user's location once it's available!
	// // map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
	// // location.getLatitude(), location.getLongitude()),
	// // currentZoom));
	//
	// // 图形
	// // GMapSharp.getInstance().addPolyline(map,location);
	// // addPolygons(location);
	// // addCircle(location);
	//
	// }
	// }
	//
	// @Override
	// public void onProviderDisabled(String provider) {
	// Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
	// }
	//
	// @Override
	// public void onProviderEnabled(String provider) {
	// Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
	// }
	//
	// @Override
	// public void onStatusChanged(String provider, int status, Bundle extras) {
	// Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
	// }

	@Override
	public void onClick(View v) {
		// 屏幕下方的5个按钮
		switch (v.getId()) {
		case R.id.button1:
			BigBanDialog bigBanDialog = new BigBanDialog(this, getResources(),
					map);
			bigBanDialog.show();
			break;
		case R.id.button2:

			break;
		case R.id.button3:
			TreesDialog treeDialog = new TreesDialog(this, getResources(), map);
			treeDialog.show();
			break;
		case R.id.button4:
			RoadsDialog roadsDialog = new RoadsDialog(this, getResources(), map);
			roadsDialog.show();
			break;
		case R.id.button5:
			PositionsDialog positionsDialog = new PositionsDialog(this,
					getResources(), map);
			positionsDialog.show();
			break;
		case R.id.btn_title_markers:

			break;
		case R.id.btn_title_layers:

			break;
		case R.id.btn_title_location:

			break;
		default:
			break;
		}
	}

}
